/**
 *
 * Copyright 2016-present reading
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import React from "react";
import PropTypes from "prop-types";
import {BackAndroid, StyleSheet, View, WebView} from "react-native";
import LoadingView from "../../common/component/LoadingView";


let canGoBack = false;

class WebViewPage extends React.Component {

    static propTypes = {
        title: PropTypes.string,
        url: PropTypes.string,
    };

    constructor(props) {
        super(props);
        this.goBack = this.goBack.bind(this);
    }

    componentDidMount() {
        BackAndroid.addEventListener('hardwareBackPress', this.goBack);
    }

    componentWillUnmount() {
        BackAndroid.removeEventListener('hardwareBackPress', this.goBack);
    }


    onNavigationStateChange(navState) {
        canGoBack = navState.canGoBack;
    }

    goBack() {
        if (canGoBack) {
            this.webview.goBack();
            return true;
        }
        return false;
    }


    renderLoading() {
        return <LoadingView />;
    }


    render() {
        return (
            <View style={styles.container}>
                <WebView
                    ref={(ref) => {
                        this.webview = ref;
                    }}
                    automaticallyAdjustContentInsets={false}
                    style={styles.base}
                    source={{uri: this.props.url}}
                    javaScriptEnabled
                    domStorageEnabled
                    startInLoadingState
                    scalesPageToFit
                    decelerationRate="normal"
                    onNavigationStateChange={this.onNavigationStateChange}
                    onShouldStartLoadWithRequest={() => {
                        return true;
                    }}
                    renderLoading={this.renderLoading}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    base: {
        flex: 1
    },
    container: {
        flex: 1,
        backgroundColor: '#FFF'
    },
});

export default WebViewPage;
